package com.bookmall.member.web;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bookmall.common.constant.ExceptionTypeConstants;
import com.bookmall.common.exception.LoginException;
import com.bookmall.member.domain.vo.RegisterUserVo;
import com.bookmall.member.service.IMemberInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author 胡菜鸡
 * @Create 2022-04-02-9:19
 */
@Controller
@RequestMapping("/member/web")
public class registerController {

    @Autowired
    private IMemberInfoService memberInfoService;

    /**
     * 注册功能
     * @author 胡菜鸡
     * @date 2022/4/2 14:20
     */
    @PostMapping("/register")
    public String register(@Valid RegisterUserVo registerUserVo, BindingResult result, RedirectAttributes redirectAttributes) {
        //如果 @Valid 的表单校验不通过
        if(result.hasErrors()){
            //将错误信息收集起来以map形式返回给注册页面
            Map<String, String> errors = new HashMap<>();
            for (FieldError fieldError : result.getFieldErrors()) {
                errors.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            //重定向携带数据（携带的数据被取出后就会就会删除，因此会有分布式多线程问题）
            //TODO 解决分布式问题
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:/register.html";
        }

        /*
            真正的注册
         */
        //TODO 1、校验验证码
        //2、进行注册（在数据库保存一个会员信息）
        try {
            return saveMember(registerUserVo, redirectAttributes);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return "redirect:/register.html";
        }
    }

    private String saveMember(RegisterUserVo registerUserVo, RedirectAttributes redirectAttributes) throws IllegalAccessException {
        try {
            memberInfoService.register(registerUserVo);
            return "redirect:/login.html";  //注册成功转到登录页
        } catch (LoginException e){
            Map<String,String> errors = new HashMap<>();
            //出现登录异常，则将异常信息发送回去
            if(e.getCode().equals(ExceptionTypeConstants.STUDENT_ID_EXIST)){
                errors.put("stuId", e.getMessage());
            } else if(e.getCode().equals(ExceptionTypeConstants.PHONE_EXIST)){
                errors.put("phone", e.getMessage());
            }
            //返回错误信息
            redirectAttributes.addFlashAttribute("errors", errors);

            //将原先填入表格的数据也发送回去
            Map<String, String> data = new HashMap<>();
            for (Field field : registerUserVo.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                data.put(field.getName(), StringUtils.toStringTrim(field.get(registerUserVo)));
            }
            //返回数据信息
            redirectAttributes.addFlashAttribute("data", data);
            return "redirect:/register.html";
        } catch (Exception e){
            //出现其他异常，报错并返回
            System.out.println(e.getStackTrace());
            return "redirect:/register.html";
        }
    }

}
